﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LIMS.Shared;
using LIMS.Entities;

namespace LIMS.Windows
{
    public partial class ChangeUserPassword : Form
    {
        public ChangeUserPassword()
        {
            InitializeComponent();
        }

        private void btnchangePassword_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtOldPassword.Text.Trim()) || string.IsNullOrEmpty(txtPassword.Text.Trim()) ||
                    string.IsNullOrEmpty(txtConfirmPassword.Text.Trim()))
                {
                    MessageBox.Show("Fill mandatory(*) information.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (SharedResource.gLoggedinUser.Password.Equals(Resource.GenerateSHAPasswordHash(txtOldPassword.Text)))
                {
                    if (txtConfirmPassword.Text != txtPassword.Text)
                    {
                        MessageBox.Show("Passwords do not match.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtOldPassword.Text = string.Empty;
                        txtConfirmPassword.Text = string.Empty;
                        txtPassword.Text = string.Empty;
                        txtOldPassword.Focus();
                        return;
                    }
                    else
                    {
                       SharedResource.gLoggedinUser.Password =  Resource.GenerateSHAPasswordHash(txtPassword.Text);
                        
                        if (SharedResource.UpdateUser(SharedResource.gLoggedinUser))
                        {
                            MessageBox.Show("Password changed successfully.", "Change password", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.Close();
                        }

                    }
                }
                else
                {
                    MessageBox.Show("Old password is incorrect.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtOldPassword.Text = string.Empty;
                    txtConfirmPassword.Text = string.Empty;
                    txtPassword.Text = string.Empty;
                    txtOldPassword.Focus();
                    return;
                }

            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
